// pages/heafood/index.js

Page({
  data: {
    nowIndex:0,
    mealType:'',
    addMeal:{
      mealName:"",
      mealCal:0,
      mealIng:"",
      mealCb:0,
      mealProtein:0,
      mealFat:0,
      type:"",
      modalImageList:[],
      mealCou:0
    },
    mealDetail:{
      name: "", 
      id:"",
      calories: 0,
       image: "",
       count:0,
       ingredient:"",
       carbohydrate:0,
       protein:0,
       fat:0,
       nowIndex:0
    },
    leftView: false,
    showCanvas:true,
    showDialog:false,
    completePercent2:60.18,//圆环B的动态值
    totalCarbohydrate:71.2,
    totalProtein:58.9,
    totalFat:49.1,
    breakfastCal:301,
    lunchCal:301,
    dinnerCal:301,
    dietlist:[
      {
          imgs:'../../images/heafood/breakfast.png',
          name:"早餐",
      },
      {
          imgs:'../../images/heafood/lunch.png',
          name:"午餐",
      },
      {
          imgs:'../../images/heafood/dinner.png',
          name:"晚餐",
      },
],
        selectedDate: '2024-07-27',  // 示例日期
        foodIntake: 1500,  // 示例食物摄入量
        exerciseConsumption: 500,  // 示例运动消耗量
        remainingCalories: 1500,  // 示例剩余可摄入量
        totalCalories: 2500, // 总卡路里

        // 日历
        weekDays: [],
        currentDateIndex: null,
        
        // 饮食推荐   //目前仅为案例
        breakfast: [
          // { name: "燕麦粥", calories: "150kcal", image: "../../images/heafood/oatmealpng.png",count:1,ingredient:"" },
          // { name: "鸡蛋白煮", calories: "70kcal", image: "../../images/heafood/breakfast.png",count:1,ingredient:"" }
        ],
        lunch: [
          // { name: "鸡胸肉", calories: "200kcal", image: "../../images/heafood/chicken.png",count:1,ingredient:"" },
          // { name: "汤", calories: "100kcal", image: "../../images/heafood/soup.png",count:1 ,ingredient:""}
        ],
        dinner: [
          // { name: "烤鱼", calories: "250kcal", image: "../../images/heafood/fish.png",count:1,ingredient:"" },
          // { name: "清炒菠菜", calories: "80kcal", image: "../../images/heafood/vegetable.png",count:1,ingredient:"" }
        ]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.updateWeekDays();
    this.updateMeal();
    this.getsumMeal();
    this.gethreeMeal();
    
    // this.drawDoughnutChart();
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
  },
  onShow(){
    this.updateWeekDays();
    this.getRingsB();
  },

  updateWeekDays() {
    const currentDate = new Date();
    const currentDayIndex = currentDate.getDay(); // 0 (Sun) to 6 (Sat)
    const startOfWeek = new Date(currentDate);
    startOfWeek.setDate(currentDate.getDate() - currentDayIndex + 1); 

    const weekDays = Array.from({ length: 7 }, (_, i) => {
      const date = new Date(startOfWeek);
      date.setDate(startOfWeek.getDate() + i);
      return {
        day: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'][i],
        date: date.getDate(),
      };
    });

    this.setData({
      weekDays,
      currentDateIndex: currentDayIndex == 0 ? 6 : currentDayIndex - 1, 
    });
    this.setData({
      nowIndex:this.data.currentDateIndex
    })
  },

  selectDate(event) {
    const index = event.currentTarget.dataset.index;
    this.setData({nowIndex:index});
    this.updateMeal();
    this.getsumMeal();
  },
    // 绘制环形图
  getRingsB(){
    this.canvasRing2 = this.selectComponent("#canringB");
    this.canvasRing2.drawCanvasRing()//绘制圆环B
  },
  //计算三餐卡路里
  async gethreeMeal(){
    const {nowIndex}=this.data;
    try {
      const result = await wx.cloud.callFunction({
        name: 'getThreeMeal',
        data: {}
      });
      console.log(result.result);
      const {list}=result.result;
      let flag0=0,flag1=0,flag2=0;
      list.forEach(item=>{
        if(item._id.nowIndex==nowIndex){
          if(item._id.type=="早餐"){
            flag0=1;
            this.setData({
                breakfastCal:item.oneCal
            })
          }
          else if(item._id.type=="午餐"){
            flag1=0;
            this.setData({
                lunchCal:item.oneCal
            })
          }
          else if(item._id.type=="晚餐"){
            flag2=0;
            this.setData({
              dinnerCal:item.oneCal
          })
          }
          this.getRingsB();
        }
          })
      if(!flag0){
        this.setData({
         breakfastCal:0
          })
      }
      if(!flag1){
        this.setData({
         lunchCal:0
          })
      }
      if(!flag2){
        this.setData({
         dinnerCal:0
          })
      }
    } catch (err) {
      console.error(err);
    }
  },
  //计算总数
  async getsumMeal(){
    try {
      const result = await wx.cloud.callFunction({
        name: 'sumMealcomponent',
        data: {}
      });
      console.log(result.result);
      const {list}=result.result;
      let flag=0;
      list.forEach(item=>{
        if(item._id.nowIndex==this.data.nowIndex){
          flag=1;
          this.setData({
            totalCarbohydrate:item.totalCb,
            totalFat:item.totalFat,
            totalProtein:item.totalProtein,
            foodIntake:item.totalCal,
            remainingCalories:1500-item.totalCal-this.data.exerciseConsumption*0.9,
            completePercent2:Math.round(item.totalCal/1500*10000)/100.00
          })
          this.getRingsB();
        }
      })
      if(!flag){
        this.setData({
          totalCarbohydrate:0,
          totalFat:0,
          totalProtein:0,
          foodIntake:0,
          remainingCalories:1500,
          completePercent2:0,
          exerciseConsumption:0
          })
      }
    } catch (err) {
      console.error(err);
    }
  },
  //获取今日食物数据渲染列表
  async updateMeal(){
    try {
      let {nowIndex}=this.data;
      let types=["早餐","午餐","晚餐"];
      for(let i=0;i<3;i++){
        const type=types[i];
        const result = await wx.cloud.callFunction({
        name: 'getMeal',
        data: {nowIndex,type}
      });
      const {data}=result.result;
      if(i==0){
        this.setData({breakfast:data})
      }
      else if(i==1){
        this.setData({lunch:data})
      }
      else{
        this.setData({dinner:data})
      }
      }
  }catch(err){
      console.log(err)
  }
},
  // 用户自行添加食物
    addFood(event) {
      this.setData({mealType:event.currentTarget.dataset.mealtype});
      this.setData({showDialog:true,showCanvas:false});
    },
    onPut(){
      var that = this;
      wx.chooseMedia({
        count: 1,
        mediaType: ['image','video'],
        sourceType: ['album', 'camera'],
        // maxDuration: 30,
        // camera: 'back',
        success:(res) => {
          var newImgsList = [];
          res.tempFiles.forEach(item=>{
            wx.showLoading({
              title: '图片上传中',
            })
              wx.cloud.uploadFile({
                // 指定上传到的云路径
                cloudPath: `mealImage/${Math.floor(Math.random()*10000)}-${new Date().getTime()}.png`,
                // 指定要上传的文件的小程序临时文件路径
                filePath: item.tempFilePath,
                // 成功回调
                success: res => {
                  console.log('上传成功', res)
                  newImgsList.push(res.fileID);
                  that.setData({
                    'addMeal.modalImageList': newImgsList
                  });
                  wx.hideLoading();
                },
                fail:err=>{
                  console.error(err)
              }
              })
          })
        }
      });
    },
    deleteImage(e){
      let {index}=e.currentTarget.dataset;
      this.setData({"addMeal.modalImageList":[]});
    },
    onNameInput(event){
      var that=this;
      var mealname=event.detail.value
      that.setData({
        'addMeal.mealName':mealname
      })
   },
   onCaloriesInput(event){
    this.setData({
        'addMeal.mealCal':event.detail.value
    })
 },
 onIngredientInput(event){
  this.setData({
    'addMeal.mealIng':event.detail.value
})
 },
 onCbInput(event){
  this.setData({
    'addMeal.mealCb':event.detail.value
})
 },
 onFatInput(event){
  this.setData({
    'addMeal.mealFat':event.detail.value
})
 },
 onProteinInput(event){
  this.setData({
    'addMeal.mealProtein':event.detail.value
})
 },
    onCancel(){
      this.setData({showDialog:false,showCanvas:true});
      this.getRingsB();
    },
    async onConfirm(){
      let {addMeal}=this.data;
      if(!addMeal.mealIng||!addMeal.mealCb||!addMeal.mealFat||!addMeal.mealName||!addMeal.mealCal||!addMeal.mealProtein||addMeal.modalImageList.length==0){
        wx.showToast({
          title: '请将全部的项填写完毕后再确认！',
          icon: 'none'
        });
      }
      else{
        this.setData({
          'addMeal.type':this.data.mealType,
          'addMeal.nowIndex':this.data.nowIndex
      });
        try {
          let {addMeal}=this.data;
          const result = await wx.cloud.callFunction({
            name: 'addmeal',
            data: {addMeal}
          });
          this.updateMeal();
        } catch (err) {
          console.error(err);
        }
      }
        this.setData({'addMeal.modalImageList':[]})
        this.setData({showDialog:false,showCanvas:true});
        this.getRingsB();
        wx.showToast({
          title: '添加成功！',
          icon: 'none'
        });
    },
    deleteMeal(event){
      const {_id}=event.currentTarget.dataset.meal;
        wx.showModal({
          title: '您确定要删除该食物吗',
          content: '',
         complete:  async (res) => {
            if (res.confirm) {
              try {
                const result = await wx.cloud.callFunction({
                  name: 'deleteMeal',
                  data: {_id}
                });
                wx.showToast({
                  title: '删除成功！',
                })
                this.updateMeal();
              } catch (err) {
                console.error(err);
              }
            }
          }
        })
    },
    changeMealDetail(event){
          const {mealCalories,mealcb,mealcou,mealfat,mealimg,mealingredient,mealname,mealprotein,_id}=event.currentTarget.dataset.meal;
          this.setData({
            'mealDetail.name':mealname,
            'mealDetail.calories':mealCalories,
            'mealDetail.image':mealimg,
            'mealDetail.count':mealcou,
            'mealDetail.ingredient':mealingredient,
            'mealDetail.carbohydrate':mealcb,
            'mealDetail.protein':mealprotein,
            'mealDetail.fat':mealfat,
            'mealDetail.nowIndex':this.data.nowIndex,
            'mealDetail.id':_id,
          })
          this.setData({
            leftView: !this.data.leftView,
            showCanvas:false
          })
      
    },
    hideLeft(){
      this.setData({
        leftView: !this.data.leftView,
        showCanvas:true
      })
      this.getRingsB();
    },
    addCount(){
      this.setData({
        "mealDetail.count":this.data.mealDetail.count+1
      });
    },
    subCount(){
      if(this.data.mealDetail.count>0){
        this.setData({
          "mealDetail.count":this.data.mealDetail.count-1
        });
    }
  },
  async  saveChange(){
      this.setData({
        leftView: !this.data.leftView,
        showCanvas:true
      })
      try {
        let {mealDetail}=this.data;
        const result = await wx.cloud.callFunction({
          name: 'updateMeal',
          data: {mealDetail}
        });
        this.updateMeal();
      } catch (err) {
        console.error(err);
      }
      this.getRingsB();
    }

  });